package com.example.zzl.view.activity.SearchActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zzl.R;
import com.example.zzl.adapter.SearchFragment.GridViewSRAdapter;
import com.example.zzl.app.MyApplication;
import com.example.zzl.databinding.ActivitySearchResultBinding;
import com.example.zzl.model.cans.Cans;
import com.example.zzl.utils.StatusBarUtils;
import com.example.zzl.view.fragment.SearchFragment.DrawFragment;
import com.example.zzl.viewmodel.SearchFragment.Classify;
import com.example.zzl.viewmodel.SearchFragment.ResultData;
import com.hyg.dropdownmenu.DropDownMenu;
import com.hyg.dropdownmenu.DropDownMenuUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

public class SearchResultActivity extends AppCompatActivity implements View.OnClickListener{

    private ActivitySearchResultBinding binding;
    private Intent intent;
    private DropDownMenu ddm;
    public static Handler handler,handler1;
    private Classify classify;
    public String search;
    public static String cate;
    private ArrayList<String> data1,data2;
    private GridViewSRAdapter adapter;
    public static ResultData resultData;
    private GridView gv;
    private TextView tv;
    private DrawerLayout drawerLayout;
    private FragmentManager manager;
    private String url;
    private RelativeLayout rl_no;
    private ProgressBar pb;
    private int orderBy;
    private ArrayList<Double> price;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        StatusBarUtils.setWindowStatusBarColor(SearchResultActivity.this, android.R.color.holo_red_light);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_search_result);
        init();

    }

    private void init() {
        manager = getSupportFragmentManager();
        resultData = new ResultData();
        intent = getIntent();
        search = intent.getStringExtra("search");
        if(intent.getStringExtra("type").equals("cateActivity")){
            cate = intent.getStringExtra("cate");
        }
        //Log.e("data",search);
        ddm = binding.dropDownMenu1;
        pb = binding.pbLoad;
        gv = binding.gvSr;
        gv.setEmptyView(pb);
        drawerLayout = binding.activitySearchResult;
        MyApplication.dw = drawerLayout;
        drawerLayout.requestDisallowInterceptTouchEvent(true);
        manager.beginTransaction().add(R.id.rl_sr_right, DrawFragment.getInstance()).commit();
        tv = binding.tvSr;
        rl_no = binding.rlNo;
        tv.setText(search);
        data1 = new ArrayList<>();
        data2 = new ArrayList<>();
        price = new ArrayList<>();
        data1.add("所有分类");
        data2.add("所有品牌");
        setDdm(data1,data2);
        loadData();
        binding.setMyClick(this);
        //setDdm();
    }

    private void loadData(){
        if(intent.getStringExtra("type").equals("Cate")){
            url = Cans.ALLCATE_URL + intent.getStringExtra("brandurl");
        }else if(intent.getStringExtra("type").equals("Mall")){
            url = Cans.HOTSHOP + intent.getStringExtra("mallUrl");
        }
        else {
            url = Cans.SEARCH + "'" + search + "'";
        }
        classify = new Classify(url, "Search");
        data1.clear();
        data2.clear();
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
//                if(msg.what == 0x1111 ){
//                    pb.setVisibility(View.GONE);
//                    rl_no.setVisibility(View.VISIBLE);
//                }else
                if(msg.what == 0x1121){
                    //rl_no.setVisibility(View.VISIBLE);
                    Toast.makeText(SearchResultActivity.this, "请求超时 ", Toast.LENGTH_SHORT).show();
                }
                else if(msg.what == 0x111){
                    //rl_no.setVisibility(View.GONE);
                    if(resultData.infoList!=null) {
                        adapter = new GridViewSRAdapter(SearchResultActivity.this, resultData.infoList);
                        gv.setAdapter(adapter);
                    }else {
                        pb.setVisibility(View.GONE);
                    //rl_no.setVisibility(View.VISIBLE);
                        Toast.makeText(SearchResultActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                    }
                }else if(msg.what == 0x112){
                    rl_no.setVisibility(View.GONE);
                    if(resultData.filter.size()>=3){
                        data1.add("所有分类");
                        for (int i = 0; i < resultData.filter.get(0).getListHotTag().size(); i++) {
                            data1.add(resultData.filter.get(0).getListHotTag().get(i).getStrTagName());
                        }
                        data2.add("所有品牌");
                        for (int i = 0; i < resultData.filter.get(1).getListHotTag().size(); i++) {
                            data2.add(resultData.filter.get(1).getListHotTag().get(i).getStrTagEngName());
                        }
                        setDdm(data1,data2);
                    }
                    handler1.sendEmptyMessage(0x222);
                }else if(msg.what==0x000){
                    Log.e("data",msg.obj.toString());
                    resultData.infoList.clear();
                    adapter.notifyDataSetChanged();
                    classify = new Classify(msg.obj.toString(),"Search");
                }
            }
        };
    }

    private void setDdm(final ArrayList<String> data1, final ArrayList<String> data2){
        DropDownMenuUtils.addGridList(this, ddm, new DropDownMenuUtils.OnMenuClickListener() {
            @Override
            public void onMenuClick(int viewPosition, int itemPosition) {
                if (viewPosition == 0) {
                    //Toast.makeText(SearchResultActivity.this, itemPosition, Toast.LENGTH_SHORT).show();
                    resultData.infoList.clear();
                    adapter.notifyDataSetChanged();
                    search = data1.get(itemPosition);
                    tv.setText(search);
                    classify = new Classify(Cans.SEARCH + "'" + search + "'","");
                } else if(viewPosition == 1){
                    resultData.infoList.clear();
                    adapter.notifyDataSetChanged();
                    search = data2.get(itemPosition);
                    tv.setText(search);
                    classify = new Classify(Cans.SEARCH + "'" + search + "'","");
                }else if(viewPosition == 2){
                    resultData.infoList.clear();
                    adapter.notifyDataSetChanged();
                    classify = new Classify(Cans.SEARCH_SORT+search+"&orderBy="+itemPosition,"Search");
                }
            }
        }, data1,data2,Arrays.asList("综合排序","价格由高到低","价格由低到高"));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            setResult(100,intent);
            finish();
            return true;

        }
        return false;
    }

    public static String getJson(Context mContext, String fileName) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        AssetManager am = mContext.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back_left:
                setResult(100,intent);
                finish();
                break;
            case R.id.iv_sr_right:
                drawerLayout.openDrawer(Gravity.RIGHT);
                break;
            case R.id.tv_sr:
                tv.setText("搜一搜");
                tv.setCompoundDrawables(null,null,null,null);
                tv.setBackgroundColor(Color.parseColor("#00000000"));
                tv.setTextColor(Color.GRAY);
                break;
        }
    }

}
